package com.hongtu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hongtu.dao.AccountInfoDao;
import com.hongtu.model.AccountChangeEvent;
import com.hongtu.service.AccountInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class AccountInfoServiceImpl implements AccountInfoService {


    @Autowired
    AccountInfoDao accountInfoDao;


    @Autowired
    RocketMQTemplate rocketMQTemplate;

    @Override
    public void sendUpdateAccountBalance(AccountChangeEvent accountChangeEvent) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("accountChangeEvent", accountChangeEvent);
        Message<String> build = MessageBuilder.withPayload(jsonObject.toJSONString()).build();
        /**
         * String txProducerGroup, String destination, Message<?> message, Object arg
         */
        TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction("brank1_group", "topic_txmsg", build, null);
        log.info("send transcation message body={},result{}", build.getPayload(), transactionSendResult.getSendStatus());


    }

    @Transactional
    @Override
    public void doUpdateAccountBalance(AccountChangeEvent accountChangeEvent) {
        log.info("开始更新本地事务，事务号：{}", accountChangeEvent.getTxNo());
        accountInfoDao.updateAccountBalance(accountChangeEvent.getAccountNo(), accountChangeEvent.getAmount() * -1);
//为幂等作准备
        accountInfoDao.addTx(accountChangeEvent.getTxNo());
        if (accountChangeEvent.getAmount() == 2) {
            throw new RuntimeException("bank1更新本地事务时抛出异常");
        }
        log.info("结束更新本地事务，事务号：{}", accountChangeEvent.getTxNo());
    }
}
